package com.huike.pullrefresh;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 自定义 ListView 实现下拉刷新
 */
public class PullReFreshListView extends ListView {


    private View inflate;
    private ImageView iv_dow;
    private TextView tv_pull_name;
    private int height;

    //状态
    private static final int pPULL = 0;//下载状态
    private static final int pPREPARE = 1;//下拉到放开就刷新状态
    private static final int pEND = 2;//正在刷新状态

    private int currentStaus = pPULL;//但前状态
    private RotateAnimation aniUp;//图片动画
    private RotateAnimation aniDow;

    public PullReFreshListView(Context context) {
        this(context, null);
    }

    public PullReFreshListView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public PullReFreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initHeader(context);

    }

    private void initHeader(Context context) {
        inflate = View.inflate(context, R.layout.listview_header, null);
        iv_dow = inflate.findViewById(R.id.iv_dow);
        tv_pull_name = inflate.findViewById(R.id.tv_pull_name);
        addHeaderView(inflate);//给ListView 添加头部

        inflate.measure(0,0);//要得到视图款高 就先要测量
        height = inflate.getMeasuredHeight();
        inflate.setPadding(0,-height,0,0);//使用padding 隐藏视图
        initAnim();

    }

    private  int start = -1;//初始化点击位置
    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                 start = (int) ev.getY();//得高点击的Y值
                break;
            case MotionEvent.ACTION_MOVE:
                int end = (int) ev.getY();//得移动的Y值
                int dy = end - start;//距离（下拉距离）

                if(currentStaus == pEND){//当状态为正在刷新的时候 不能在下拉 直接跳出
                   break;
                }


                int firstVisiblePosition = this.getFirstVisiblePosition();//得到item 第一个位置
                if(dy > 0 && firstVisiblePosition == 0){// 当下拉距离大于0 并且 是第一item位置的时候 进行下拉操作
                    int paddng = -height + dy;//padding值


                    if(paddng > 0 &&  currentStaus != pPREPARE ){//currentStaus != pPREPARE 是只进行一次动画切换
                        currentStaus = pPREPARE;
                        refreshState();//下拉动作
                    }else if(paddng <= 0 && currentStaus != pPULL ){
                        currentStaus = pPULL;
                        refreshState();
                    }
                    inflate.setPadding(0,paddng,0,0);

                    return  true;//消费事件

                }


                break;
            case MotionEvent.ACTION_UP:
                start = -1;
                if(currentStaus == pPREPARE){//如果状态是正在刷新的时候就
                    currentStaus = pEND;
                    inflate.setPadding(0,0,0,0);

                    refreshState();

                }else if(currentStaus == pPULL){//如果下拉距离不够 状态还是处于pPULL的时候就直接隐藏布局
                    currentStaus = pPULL;
                    inflate.setPadding(0,-height,0,0);
                    refreshState();
                }

                break;
        }

        return super.onTouchEvent(ev);
    }

    private void initAnim(){

        aniUp = new RotateAnimation(0,-180, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);

        aniDow = new RotateAnimation(-180,0,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);

        aniUp.setFillAfter(true);
        aniDow.setFillAfter(true);

        aniUp.setDuration(300);
        aniDow.setDuration(300);


    }

    //更新状态
    private void refreshState() {

        Log.e("---",currentStaus +"");

        if(currentStaus == pPULL){
            iv_dow.startAnimation(aniDow);
            tv_pull_name.setText("下拉刷新");


        }else if(currentStaus == pPREPARE){
            iv_dow.startAnimation(aniUp);
            tv_pull_name.setText("松开刷新");

        }else if( currentStaus == pEND){
            iv_dow.clearAnimation();
            iv_dow.setImageResource(R.drawable.refresh);

            RotateAnimation animation = new RotateAnimation(0,360,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
            animation.setDuration(300);
            animation.setRepeatCount(-1);
            animation.setInterpolator(new LinearInterpolator());//线性
            iv_dow.setAnimation(animation);
            tv_pull_name.setText("正在刷新");

            if(listener != null){//判断是否使用回调，防止空指针异常
                listener.onRefresh();
            }

        }

    }

    //当刷新完成时 改变正在刷新状态 回复初始化
    public void ComplenerAnimation(){
        iv_dow.clearAnimation();
        iv_dow.setImageResource(R.drawable.obu);
        tv_pull_name.setText("刷新完成！");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                iv_dow.clearAnimation();
                iv_dow.setImageResource(R.drawable.rjd_down);
                tv_pull_name.setText("下拉刷新");
                inflate.setPadding(0,-height,0,0);
                currentStaus = pPULL;
            }
        },2000);


    }

    //下拉回调
    private onRefreshListener listener;
    public void setOnRefreshListener(onRefreshListener listener){
        this.listener = listener;
    }

    public interface onRefreshListener{
        void onRefresh();
    }

}
